package action;

import Impl.TopicDaoImpl;
import Impl.plateDaoImpl;
import dao.userDao;
import entity.Admin;
import entity.Plate;
import entity.TopicInfo;
import entity.User;
import entity.page.ListPage;
import org.apache.taglibs.standard.tag.el.core.ForEachTag;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShowTopicAction")
public class ShowTopicAction extends HttpServlet {
    TopicDaoImpl topicDao = new TopicDaoImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--------正在执行ShowTopicAction--------");
        String method = request.getParameter("method");
        request.setCharacterEncoding("utf-8");
        if (method!=null&&method.equals("del")){
            System.out.println("正在删除Topic:");
            int id = Integer.parseInt(request.getParameter("id"));
            topicDao.deleteTopicById(id);
        }else {
            int pageNow = 0;
            if (request.getParameter("pageNow") == null) {
                pageNow = 1;
            } else {
                pageNow = Integer.parseInt(request.getParameter("pageNow"));
            }
            Admin admin = (Admin) request.getSession().getAttribute("admin");
            String condition = admin.getIdentity();
            System.out.println("管理员身份：" + condition);
            plateDaoImpl plateDao = new plateDaoImpl();
            List<Plate> tid = plateDao.findPlateByCondition(condition);
            List<Plate> childPlate = plateDao.findPlateByPId(tid.get(0).getSid());
            ArrayList<TopicInfo> topicInfos = topicDao.getTopicInfo(tid.get(0).getSid());
            for (Plate t :childPlate){
                ArrayList<TopicInfo> topic = topicDao.getTopicInfo(t.getSid());
                topicInfos.addAll(topic);
            }
            int allcount = topicInfos.size();
            int allpage;
            if (allcount % 5 == 0) {
                allpage = allcount / 5;
            } else {
                allpage = allcount / 5 + 1;
            }
            request.setAttribute("allcount", allcount);
            request.setAttribute("allpage", allpage);
            request.setAttribute("pageNow", pageNow);
            request.setAttribute("topicInfos", topicInfos);
            request.getRequestDispatcher("/show_topic.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
